//
//  VideoDetailVC.m
//  Tunnel
//
//  Created by wbb on 2025/7/6.
//

#import "VideoDetailVC.h"
#import "ThreeButtonTitleView.h"
#import "SJVideoPlayer.h"
#import "SDWebImage.h"
#import "GJSCImageView.h"

@interface VideoDetailCell : TYBaseTableViewCell
@property (nonatomic, strong) UILabel * titleLab;
@property (nonatomic, strong) UILabel * detailLab;
@end
@implementation VideoDetailCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        [self initUI];
    }
    return self;
}

- (void)initUI {
    UILabel *headerLab = [[UILabel alloc] init];
    headerLab.text = @"";
    headerLab.textColor = main_light_text_color_6;
    headerLab.font = [UIFont systemFontOfSize:14];
    [self.contentView addSubview:headerLab];
    self.titleLab = headerLab;
    [headerLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        
        make.centerY.offset(0);
        
    }];
    
    UILabel *detailLab = [[UILabel alloc] init];
    detailLab.text = @"";
    detailLab.textColor = main_text_color;
    detailLab.font = [UIFont systemFontOfSize:14];
    [self.contentView addSubview:detailLab];
    self.detailLab = detailLab;
    [detailLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headerLab.mas_right).offset(15);
        make.centerY.offset(0);
    }];
    
}
- (void)cellWithData:(id)data {
    [super cellWithData:data];
    
    self.titleLab.text = data[@"title"]?:@"";
    self.detailLab.text = data[@"content"]?:@"";
    
}
@end

@interface VideoDetailVC () <ThreeButtonTitleViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) ThreeButtonTitleView *titleView;
@property (nonatomic, strong) SJVideoPlayer * player;
@property (nonatomic, strong) UIView * playerView;
@property (nonatomic, copy) NSMutableArray * dataArr;
@property (nonatomic, copy) NSArray * typeList;
@property (nonatomic, strong) NSMutableDictionary * videoInfo;
@property (nonatomic, copy) NSString * videoPath;

@property (nonatomic, strong) UIImageView * headerImgView;
@property (nonatomic, strong) NSMutableArray * buttonTitles;
@end

@implementation VideoDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.dataArr = @[
        @{
            @"title":@"事件类型",
            @"content":@""
        }.mutableCopy,
        @{
            @"title":@"事件位置",
            @"content":@""
        }.mutableCopy,
        @{
            @"title":@"发生时间",
            @"content":@""
        }.mutableCopy,
    ].mutableCopy;
    // 创建自定义titleView
    NSMutableArray *buttonTitles = @[@"抓拍图片", @"实时视频", @"历史视频"].mutableCopy;
    self.buttonTitles = buttonTitles;
    if(!self.isShowHistory) {
        [buttonTitles removeObject:@"历史视频"];
    }
    if(self.isHeight) {
        [buttonTitles removeObject:@"抓拍图片"];
    }
    
    UIColor *selectedColor = main_text_color;
    UIColor *unselectedColor = [UIColor colorWithRed:42/255.0 green:42/255.0 blue:42/255.0 alpha:0.5];
    
    CGRect titleViewFrame = CGRectMake(0, 0, 220, 44);
    _titleView = [[ThreeButtonTitleView alloc] initWithFrame:titleViewFrame
                                                buttonTitles:buttonTitles
                                         selectedButtonColor:selectedColor
                                       unselectedButtonColor:unselectedColor];
    _titleView.delegate = self;
    
    // 设置为导航栏的titleView
    self.navigationItem.titleView = _titleView;
    
    
    [self initUI];
    
    
    [self getType];
}


- (void)getType {
    NSString *utlStr = [NSString stringWithFormat:@"%@%@",TYGetDictType,@"AI_EVENT_TYPE"];
    kWEAK_SELF
    [TYNetWorkTool getRequest:utlStr parameters:@{} successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.typeList = [NSArray arrayWithArray:data[@"data"]];
        [weakSelf getAiInfoRequestData];
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}

- (void)getAiInfoRequestData {
    kWEAK_SELF
    NSString *utlStr = [NSString stringWithFormat:@"%@%@",TYGetAiInfo,self.ID?:@""];
    if(_isHeight){
        utlStr = TYGetHeightOverInfo;
    }
    [TYNetWorkTool getRequest:utlStr parameters:@{
        @"heightOverId":self.ID
    } successBlock:^(BOOL success, NSDictionary * _Nonnull data, NSString * _Nonnull msg) {
        NSLog(@"%@",data);
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:data[@"data"]];
        NSMutableDictionary *dic1 = self.dataArr[0];
        NSMutableDictionary *dic2 = self.dataArr[1];
        NSMutableDictionary *dic3 = self.dataArr[2];
        
        dic2[@"content"] = [NSString stringWithFormat:@"%@ %@",dic[@"direction"]?:@"", dic[@"pileNo"]?:@""];
        
        if(weakSelf.isHeight){
            [weakSelf getHKCode:dic[@"cameraType"] callBlock:^{
                [weakSelf threeButtonTitleView:nil didSelectButtonAtIndex:0];
            }];
            dic1[@"content"] = weakSelf.eventType;

            dic3[@"content"] = dic[@"createTime"]?:@"";
            [weakSelf getHisHKCode:dic[@"cameraType"] date:dic[@"createTime"]];
        }else{
            dic1[@"content"] = [weakSelf getTypeName:dic[@"eventType"]?:@""];
            
            dic3[@"content"] = dic[@"recognizeTime"]?:@"";
            [weakSelf getHKCode:dic[@"cameraId"] callBlock:^{
                [weakSelf threeButtonTitleView:nil didSelectButtonAtIndex:0];

            }];


        }

        weakSelf.videoInfo = [NSMutableDictionary dictionaryWithDictionary:dic] ;

        [weakSelf.tableView reloadData];
        
   
        
        
        
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}
// 视频地址接口
- (void)getHKCode:(NSString *)cameraId  callBlock:(void (^)(void))callBlock{
    kWEAK_SELF;
    [TYNetWorkTool postRequest:@"/app/camera/getHKCode" parameters:@{
        @"cameraId":cameraId?:@""
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.videoPath = data[@"data"][@"url"]?:@"";
        if(callBlock){
            callBlock();
        }
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}
-(void)getHisHKCode:(NSString*)cameraId date:(NSString*)dateStr{
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate * date = [dateFormatter dateFromString:dateStr];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.minute = -5;  // 负数表示向前偏移（过去的时间）
    NSDate *fiveMinutesAgo = [calendar dateByAddingComponents:components toDate:date options:0];
    components.minute = 5;
    NSDate *fiveMinutesAfter = [calendar dateByAddingComponents:components toDate:date options:0];
    [dateFormatter setDateFormat:@"yyyy-MM-dd+HH:mm:ss"];
    
    
    
    
    kWEAK_SELF;
    [TYNetWorkTool postRequest:@"/app/camera/getHisHKCode" parameters:@{
        @"cameraId":cameraId?:@"",
        @"beginTime":[dateFormatter stringFromDate:fiveMinutesAgo],
        @"endTime":[dateFormatter stringFromDate:fiveMinutesAfter],
    } successBlock:^(BOOL success, id  _Nonnull data, NSString * _Nonnull msg) {
        weakSelf.videoInfo[@"videoUrl"] = data[@"data"][@"url"]?:@"";
    } failureBlock:^(NSString * _Nonnull description) {
        
    }];
}

- (NSString *)getTypeName:(NSString *)eventType {
    for (int i = 0; i<self.typeList.count; i++) {
        NSDictionary *dic = self.typeList[i];
        if([dic[@"dictValue"] isEqualToString:eventType]) {
            return dic[@"dictLabel"]?:@"";
        }
    }
    return @"";
}
- (void)setPlayerViewWithUrl:(NSURL *)URL {
    if(self.playerView.subviews && self.playerView.subviews > 0){
        for (UIView *view in self.playerView.subviews) {
            [view removeFromSuperview];
        }
    }
    
    SJPlayModel *playModel = [SJPlayModel UITableViewHeaderViewPlayModelWithPlayerSuperview:self.playerView tableView:self.tableView];
    _player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:URL playModel:playModel];
}
- (void)setImgView:(NSURL *)URL {
    if(self.playerView.subviews && self.playerView.subviews > 0){
        for (UIView *view in self.playerView.subviews) {
            [view removeFromSuperview];
        }
    }
    self.headerImgView = nil;
    UIImageView *headerImgView = [[UIImageView alloc] init];
    [self.playerView addSubview:headerImgView];
    self.headerImgView = headerImgView;
    [headerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.playerView);
    }];
    
    [headerImgView sd_setImageWithURL:URL];
    [headerImgView setUserInteractionEnabled:YES];
    [headerImgView addTarget:self action:@selector(imgClick)];
}
- (void)imgClick {
    [self openImgView:self.headerImgView.image];
}
- (void)openImgView:(UIImage *)image {
    GJSCImageView *scImgView = (GJSCImageView *)[GJSCImageView nibView];
    [kWindow addSubview:scImgView];
    [scImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.offset(0);
    }];
    scImgView.image = image;
}
#pragma mark - ThreeButtonTitleViewDelegate

- (void)threeButtonTitleView:(UIView *)titleView didSelectButtonAtIndex:(NSInteger)index {
    NSLog(@"选中了按钮 %ld", (long)index);
    NSString * title = self.buttonTitles[index];
    // 根据选中的按钮索引执行相应的操作
    if([title isEqualToString:@"抓拍图片"]){
        // 选项一的处理逻辑
        NSURL *url = [NSURL URLWithString:self.videoInfo[@"imageUrl"]?:@""];
        [self setImgView:url];
    }else if ([title isEqualToString:@"实时视频"]){
        NSURL *url = [NSURL URLWithString:self.videoPath];
        [self setPlayerViewWithUrl:url];
    }else if ([title isEqualToString:@"历史视频"]){
        NSString *urlStr = self.videoInfo[@"videoUrl"]?:@"";
        NSURL *url = [NSURL URLWithString:urlStr];
        [self setPlayerViewWithUrl:url];
    }

}
#pragma mark ---- UITableViewDelegate, UITableViewDataSource ----
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[VideoDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row < self.dataArr.count) {
        NSMutableDictionary *dic = self.dataArr[indexPath.row];
        //        cell.textLabel.text = dic[@"title"];
        [cell cellWithData:dic];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
#pragma mark ---- lazy ----
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        //        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = main_background_color;
    }
    return _tableView;
}

- (void)initUI {
    _player = [SJVideoPlayer player];
    _player.defaultEdgeControlLayer.automaticallyShowsPictureInPictureItem = NO;

    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.tableView.tableFooterView = [UIView new];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_WIDTH * 245/375.f)];
    headerView.backgroundColor = main_background_color;
    
    UIView *playerView = [[UIView alloc] init];
    [headerView addSubview:playerView];
    self.playerView = playerView;
    [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.offset(-34);
    }];
    
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"事件信息";
    titleLab.font = [UIFont systemFontOfSize:17];
    titleLab.textColor = main_text_color;
    [headerView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.bottom.offset(-10);
    }];
    
    self.tableView.tableHeaderView = headerView;
    
    
    
    
}
@end
